<?php
class TTrie
{
    private $dict = [[]]; //字典
    private $input = 0; //字符串当前偏移
    private $backtracking = 0; //字符串回溯位置
    private $buffer = [];

//    public function __construct($words)
//    {
//        $this->insert($words);
//    }

    /**
     * 插入单词
     * Function insert
     * @Author sakmon
     * @CreateTime 2019/4/25 15:42
     * @param $word
     */
    public function insert($word=null)
    {
        if (is_array($word)) {
            foreach ($word as $v) {
                $this->insert($v);
            }
            return;
        }
        $p = count($this->dict);
        echo $p;
        $cur = 0; //当前节点号
        foreach (str_split($word) as $c) {
            if (isset($this->dict[$cur][$c])) { //已存在就下移 , 相同前缀单词同一个节点
                $cur = $this->dict[$cur][$c];
                continue;
            }
            $this->dict[$p] = []; //创建新节点
            $this->dict[$cur][$c] = $p; //在父节点记录子节点号
            $cur = $p; //把当前节点设为新插入的
            $p++;
        }
        $this->dict[$cur]['isWord'] = true; //一个词结束，标记叶子节点
    }
    public function get(){
        return $this->dict;
    }
}
$trie = new TTrie();
$words = ['abd', 'abc', 'bd', 'dd', 'dda'];
foreach ($words as $word) {
    $trie->insert($word);
}
 $arr=$trie->get();
echo '<pre>';
var_dump($arr);
echo '</pre>';

